﻿using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinServer
{
    public partial class FrmServer : Form
    {
        public FrmServer()
        {
            InitializeComponent();
        }
        /// <summary>
        /// signalR服务
        /// </summary>
        public IDisposable signalR { get; set; }

        private void FrmServer_Load(object sender, EventArgs e)
        {
            StartSignalR();
        }

        private void StartSignalR()
        {
            //signalr的发布
            var signalUrl = "http://localhost:1245";
            signalR = WebApp.Start(signalUrl);//开启服务
            WriteLog($"服务启动成功：{signalUrl}");

            btnStart.Enabled = false;
        }

        public void WriteLog(object obj)
        {
            this.Invoke(new Action(() =>
            {
                txtMessage.AppendText($"{DateTime.Now:HH:mm:ss}：{obj}\r\n\r\n");
            }));
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            StartSignalR();
        }

        private async void btnStop_Click(object sender, EventArgs e)
        {
            if (signalR != null)
            {
                //向客户端广播消息
                IHubContext _myHubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
                await _myHubContext.Clients.All.SendClose("服务端已关闭");
                signalR.Dispose();

                btnStart.Enabled = true;

                WriteLog("服务端已关闭");
            }
        }

        private async void btnSend_Click(object sender, EventArgs e)
        {
            string txt = txtSend.Text;
            IHubContext _myHubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
            await _myHubContext.Clients.All.Update(txt);
            WriteLog($"广播成功：{txt}");
        }
    }
}
